package com.bosssoft.trainee.until;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.bosssoft.trainee.entity.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author liuqiang
 * @date 2022/7/5 9:44
 * 生成JWT token
 */
@Component
@Slf4j
public class JwtUntil {

    //私钥
    private static final String TOKEN_SECRET = "admin123";

    /**
     * 生成token，自定义过期时间 毫秒
     *
     * @param user
     * @return String
     */
    public static String getToken(User user) {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60 * 60 * 1000;//一小时有效时间
        Date end = new Date(currentTime);
        String token = "";
        token = JWT.create()
                .withAudience(user.getUserId().toString())  //设置 载荷 签名的观众 也可以理解谁接受签名的
                .withIssuedAt(start)    //设置 载荷 生成签名的时间
                .withExpiresAt(end)     //设置过期时间
//                .sign(Algorithm.HMAC256(user.getUserPassword()));   //signature加密
                .sign(Algorithm.HMAC256(TOKEN_SECRET));   //signature加密

        return token;
    }
}
